package nave.model;

import java.util.Random;

import nave.Constants;
import nave.Point;
import nave.control.Options;


public class Enemy extends Spaceship {

	/*
	 * Attributes
	 */
	private static int idCounter = Constants.ID_ENEMY_BASE;
	private static Random randomGenerator = new Random();
	
	/*
	 * Constants
	 */
	public static int CHANCE_OF_CHANGING_DIRECTION = 1; // in percent
	
	/*
	 * Constructor
	 */
	public Enemy( int numberOfBullets ) {
		super( idCounter++, numberOfBullets );
	}
	
	/*
	 * Public methods
	 */
	public static void resetIdCounter() {
		idCounter = Constants.ID_ENEMY_BASE;
	}
	
	public void getNewDirection() {
		int aux = 0;
		
		// if the enemy is stopped, it will change the direction
		if ( deltaMove.equals(new Point(0,0)) )
			aux = randomGenerator.nextInt(5) - 2;
		else
		{
			float temp = 500.0f / CHANCE_OF_CHANGING_DIRECTION;
			aux = (int) (randomGenerator.nextInt( (int) temp ) - temp / 2);
		}
		
		switch (aux) {
			case DIRECTION_UP:
			case DIRECTION_DOWN:
			case DIRECTION_LEFT:
			case DIRECTION_RIGHT:
				nextDirection = aux;
		}
	}
	
	@Override
	public void placeOnStage() {
		int rowsAux = 0,
			colsAux = 0;
		do
		{
			rowsAux = randomGenerator.nextInt( Stage.getRows() );
			colsAux = randomGenerator.nextInt( Stage.getCols() );
		} while ( Stage.getPositionOnStage(rowsAux, colsAux ) != Constants.EMPTY );
		
		position.setLocation(colsAux, rowsAux);
		
		Stage.setPositionOnStage( position, getId() );
	}
	
	@Override
	public void explode() {
		Player.score(Constants.POINTS_ENEMY_DIED);

		finishMove();
		Stage.setPositionOnStage(position, Constants.EMPTY);

		isExploding = true;
	}

	public Shot intelligence(int stageNumber)
	{
		if ( ! deltaMove.equals(new Point(0,0)) )
		{
			Point temp = (Point) position.clone();
			do
			{
				temp.translate(deltaMove);
			} while ( Stage.getPositionOnStage( temp ) == Constants.EMPTY );

			int difficulty = Options.getDifficulty();
			if ( Stage.getPositionOnStage( temp ) == Constants.ID_PLAYER )
			{
				switch (difficulty)
				{
				case Options.EASY:
					if ( randomGenerator.nextInt(Constants.ENEMY_STUPIDITY * 2) - stageNumber <= 0 )
						return shot();
					break;
				case Options.MEDIUM:
					if ( randomGenerator.nextInt(Constants.ENEMY_STUPIDITY) - stageNumber <= 0 )
						return shot();
					break;
				case Options.HARD:
					return shot();
				}
			}
			else if ( difficulty == Options.EASY && randomGenerator.nextInt( Constants.ENEMY_STUPIDITY * 3 ) == 0 )
				return shot();
		}
		return null;
	}

	/*
	 * Private methods
	 */
	@Override
	protected void extra() {
		getNewDirection();
	}
}
